package cn.digger.md2pdf.util;

import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;

public class Md2HtmlUtil {

    private static final Parser PARSER = Parser.builder().build();
    private static final HtmlRenderer RENDERER = HtmlRenderer.builder().build();

    private Md2HtmlUtil() {
        throw new RuntimeException("Md2HtmlUtil can't instantiate!");
    }

    public static String convertMd2Html(String markdown) {
        String htmlBody = RENDERER.render(PARSER.parse(markdown));
        return wrapWithHtmlDocument(htmlBody);
    }

    /**
     * 将 HTML 片段包装成完整的 HTML 文档
     */
    /*private static String wrapWithHtmlDocument(String bodyContent) {
        return "<!DOCTYPE html>\n" +
                "<html>\n" +
                "<head>\n" +
                "    <title>Document</title>\n" +
                "</head>\n" +
                "<body>\n" +
                bodyContent +
                "\n</body>\n</html>";
    }*/

    private static String wrapWithHtmlDocument(String bodyContent) {
        return "<!DOCTYPE html>\n" +
                "<html lang=\"zh-CN\">\n" +  // 添加语言声明
                "<head>\n" +
                "    <meta charset=\"UTF-8\"/>\n" +
                "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n" +  // 双重保险
                "    <title>Document</title>\n" +
                "</head>\n" +
                "<body>\n" +
                bodyContent +
                "\n</body>\n</html>";
    }
}